package com.gt.xmall.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.gt.xmall.model.SysUser;
import com.gt.xmall.repository.SysUserDao;
import com.gt.xmall.util.StringUtil;


/**
 * 用户管理类.
 * 
 * @author Junfeng.W
 */
//Spring Service Bean的标识.
@Component
@Transactional(readOnly = true)
public class AccountService {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	private static Logger logger = LoggerFactory.getLogger(AccountService.class);

	private SysUserDao sysUserDao;

	public List<SysUser> getAllUser() {
		return (List<SysUser>) sysUserDao.findAll();
	}

	public SysUser getUser(Long id) {
		return sysUserDao.findOne(id);
	}

	public SysUser findUserByName(String loginName) {
		return sysUserDao.findByName(loginName);
	}

	@Transactional(readOnly = false)
	public void registerUser(SysUser user) {
		entryptPassword(user);
		sysUserDao.save(user);
	}

	@Transactional(readOnly = false)
	public void updateUser(SysUser user) {
		if (StringUtils.isNotBlank(user.getPlainPassword())) {
			entryptPassword(user);
		}
		sysUserDao.save(user);
	}

	@Transactional(readOnly = false)
	public void deleteUser(Long id) {
		if (isSupervisor(id)) {
			logger.warn("操作员{}尝试删除超级管理员用户", getCurrentUserName());
			throw new ServiceException("不能删除超级管理员用户");
		}
		sysUserDao.delete(id);
	}

	/**
	 * 判断是否超级管理员.
	 */
	private boolean isSupervisor(Long id) {
		return id == 1;
	}

	/**
	 * 取出Shiro中的当前用户LoginName.
	 */
	private String getCurrentUserName() {
		SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
		return user.getName();
	}

	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(SysUser user) {
		String password = StringUtil.encodePassword(user.getPlainPassword(), "MD5");
		user.setPassword(password);
	}

	@Autowired
	public void setSysUserDao(SysUserDao sysUserDao) {
		this.sysUserDao = sysUserDao;
	}

	
}
